package com.cal.utms.dao.maintenance;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.cal.utms.entity.CreditRating;
import com.cal.utms.entity.Issuer;
import com.cal.utms.entity.IssuerBankAccount;
import com.cal.utms.entity.IssuerContactPerson;
import com.cal.utms.entity.IssuerType;
import com.cal.utms.logAudit.AuditLogInterceptor;
import com.cal.utms.util.HibernateUtil;

public class IssuerDaoImpl implements IssuerDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<IssuerType> getAllIssuerType() {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<IssuerType> issuerTypes = new ArrayList<IssuerType>();
		try {
			tx = session.beginTransaction();
			issuerTypes = session.createQuery("from IssuerType").list();
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return issuerTypes;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CreditRating> getAllCreditRating() {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<CreditRating> creditRatings = new ArrayList<CreditRating>();
		try {
			tx = session.beginTransaction();
			creditRatings = session.createQuery("from CreditRating").list();
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return creditRatings;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Issuer> getAllIssuers() {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<Issuer> issuers = new ArrayList<Issuer>();
		try {
			tx = session.beginTransaction();
			issuers = session.createQuery("from Issuer").list();
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return issuers;
	}

	@SuppressWarnings("unchecked")
	public List<Issuer> getAllPrimaryDealers() {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<Issuer> issuers = new ArrayList<Issuer>();
		List<IssuerType> issuerTypes;
		try {
			tx = session.beginTransaction();
			issuerTypes = session.createQuery("from IssuerType i where i.primaryDealer=1").list();
			for (IssuerType issuerType : issuerTypes) {
				Query query = session.createQuery("from Issuer i where i.issuerType=:issuerType");
				query.setParameter("issuerType", issuerType.getId());
				List<Issuer> tempIssuers = query.list();
				for (Issuer issuer : tempIssuers) {
					issuers.add(issuer);
				}
			}
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return issuers;
	}

	public Issuer getById(Integer id) {
		Session session = HibernateUtil.getSession().openSession();
		Issuer issuer = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			issuer = (Issuer) session.get(Issuer.class, id);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			System.out.println("Exception getByID Issuer " + e.getMessage());
		} finally {
			session.close();
		}
		return issuer;
	}

	public IssuerType getIssuerTypeById(Integer id) {
		Session session = HibernateUtil.getSession().openSession();
		IssuerType issuerType = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			issuerType = (IssuerType) session.get(IssuerType.class, id);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			System.out.println("Exception getByID IssuerType " + e.getMessage());
		} finally {
			session.close();
		}
		return issuerType;
	}

	@Override
	public Object saveIssuer(Issuer issuer) {
		AuditLogInterceptor interceptor = new AuditLogInterceptor();
		Session session = HibernateUtil.getSession().openSession(interceptor);
		interceptor.setSession(session);
		Transaction tx = null;
		Object object = null;
		try {
			tx = session.beginTransaction();
			object = session.save(issuer);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return object;
	}

	@Override
	public Issuer getIssuerByIssuerCode(String issuerCode) {
		Session session = HibernateUtil.getSession().openSession();
		Issuer issuer = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			issuer = (Issuer) session.createQuery("From Issuer I where I.code=:code").setParameter("code", issuerCode).uniqueResult();
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			System.out.println("Exception getByID Issuer " + e.getMessage());
		} finally {
			session.close();
		}
		return issuer;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<IssuerBankAccount> getBankAccountByIssuer(int issuer_id) {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<IssuerBankAccount> issuerBankAccounts = new ArrayList<IssuerBankAccount>();
		try {
			tx = session.beginTransaction();
			issuerBankAccounts = session.createQuery("FROM IssuerBankAccount B where B.issuer.id =:id").setParameter("id", issuer_id).list();
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return issuerBankAccounts;
	}

	@SuppressWarnings("unchecked")
	public List<IssuerContactPerson> getContactsByIssuer(int issuer_id) {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<IssuerContactPerson> contactPersons = new ArrayList<IssuerContactPerson>();
		try {
			tx = session.beginTransaction();
			contactPersons = session.createQuery("FROM IssuerContactPerson C where C.issuer.id =:id").setParameter("id", issuer_id).list();
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return contactPersons;
	}

	@Override
	public Object updateIssuer(Issuer issuer, List<IssuerBankAccount> accountDtos) {
		AuditLogInterceptor interceptor = new AuditLogInterceptor();
		Session session = HibernateUtil.getSession().openSession(interceptor);
		interceptor.setSession(session);
		Transaction tx = null;
		Object object = null;
		try {
			tx = session.beginTransaction();
			long count_c = ((Number) session.createQuery("select count(*) from IssuerContactPerson B where B.issuer.id =:id").setParameter("id", issuer.getId()).uniqueResult())
					.longValue();
			if (count_c > 0) {
				session.createQuery("DELETE FROM IssuerContactPerson B where B.issuer.id =:id").setParameter("id", issuer.getId()).executeUpdate();
			}
			for (IssuerBankAccount issuerBankAccount : accountDtos) {
				session.merge(issuerBankAccount);
			}

			object = session.merge(issuer);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return object;
	}

	public IssuerBankAccount getAccountById(int bankAccount) {
		Session session = HibernateUtil.getSession().openSession();
		Transaction transaction = null;
		IssuerBankAccount account = null;
		try {
			transaction = session.beginTransaction();
			account = (IssuerBankAccount) session.get(IssuerBankAccount.class, bankAccount);
			transaction.commit();
		} catch (HibernateException e) {
			if (transaction != null) {
				transaction.rollback();
			}
			e.printStackTrace();
		} finally {
			session.close();
		}
		return account;
	}

	public Object saveCategory(List<IssuerType> categoriesList) {
		AuditLogInterceptor interceptor = new AuditLogInterceptor();
		Session session = HibernateUtil.getSession().openSession(interceptor);
		interceptor.setSession(session);
		Transaction tx = null;
		Object object = null;
		try {
			tx = session.beginTransaction();
			for (IssuerType issuerType : categoriesList) {
				session.merge(issuerType);
			}
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return object;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Issuer> getUnmappedIssuers() {
		Session session = HibernateUtil.getSession().openSession();
		List<Issuer> issuers = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			issuers = session.createQuery("from Issuer I where I.code not in (select M.calIssuerCode from Issuercodemapping M)").list();
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return issuers;
	}

	@SuppressWarnings("unchecked")
	public List<Issuer> getIssuerByFundId(int id) {
		Session session = HibernateUtil.getSession().openSession();
		List<Issuer> issuers = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			issuers = session.createQuery("from Issuer I where I.issuerType in (select M.issuer.id from FundIssuerMap M where M.fund.id=:fundid)").setParameter("fundid", id)
					.list();
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return issuers;
	}

	public Issuer getMappingIssuer(String issuerCode) {
		Session session = HibernateUtil.getSession().openSession();
		Issuer issuer = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			issuer = (Issuer) session.createQuery("select M.issuer from Issuercodemapping M where M.cseIsuCode=:issuecode").setParameter("issuecode", issuerCode).uniqueResult();
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return issuer;
	}

}
